'use strict';

const Controller = require('egg').Controller,
  utils = require('../utils/utils'),
  moment = require('moment');

class StatisticsController extends Controller {
  async campaign() {
    const ctx = this.ctx;
    try {
      const body = ctx.request.body;
      this.ctx.validate({
        _id: {type: 'string', min: 24, max: 24},
      }, body);

      const data = {
        _id: body._id,
      };

      const campaignInfo = await ctx.model.Campaign.findById(data._id, {
        _id: 1,
        pcode: 1,
        start: 1,
        end: 1,
        entryUrl: 1,
        shareUrl: 1,
      });
      if (!campaignInfo) {
        throw new Error('没有这个活动');
      }


      let dateToday = moment().format('YYYY-MM-DD');
      let start_date = moment(campaignInfo.start).format('YYYY-MM-DD');
      let end_date = moment(campaignInfo.end).format('YYYY-MM-DD');
      const params = {
        idx: 'pv,uv',
        start_date: start_date,
        end_date: moment(dateToday).isBefore(end_date, 'day') ? dateToday : end_date,
      };
      const resultArr = await Promise.all([
        ctx.service.statistics.mta(params, 'ctrPage', {
          entryUrl: utils.baseUrl(campaignInfo.entryUrl),
          shareUrl: utils.baseUrl(campaignInfo.shareUrl),
        }),
        ctx.service.statistics.mta(params, 'ctrCustom', {
          banner: `${campaignInfo._id}_banner`,
          wechat: `${campaignInfo._id}_wechat`,
          timeline: `${campaignInfo._id}_timeline`,
          qq: `${campaignInfo._id}_qq`,
        }),
      ]);
      const dataFunnel = await ctx.service.statistics.dataFunnel({
        _id: campaignInfo._id,
        pcode: campaignInfo.pcode,
      });
      const mtaList = await ctx.service.statistics.mtaDataList(Object.assign(...resultArr), params.start_date, params.end_date);
      ctx.body = {
        code: 0,
        msg: '成功',
        data: {
          dataSource1: dataFunnel,
          dataSource2: mtaList,
        },
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }

  }
}

module.exports = StatisticsController;
